
import os
from urllib.parse import urlparse
import json
import paho.mqtt.client as mqtt
from setting import *
from update import UpdateSensorWebSocketClient, downland_remote_files
import threading
from ns import Ns
from gateways_upgrade import gateways_upgrade
from setting import MQTT_LOCAL_PUBLISH_TOPIC

# from db_function import DataBaseFunction

class SubscriptionMainBaseServer:
    '''侦听主站事务通道下达的任务'''

    def __init__(self, subscription_topic, publish_topic) -> None:

        self.publish_topic = publish_topic
        
        self.subscription_topic = subscription_topic

    def connect_mqtt(self):

        client = mqtt.Client()

        # 指定回调函数
        client.on_connect = self.on_connect
        client.on_message = self.on_message

        # 建立连接
        client.connect(MQTT_LOCAL_HOST, MQTT_LOCAL_PORT, 60)

        # 发布消息
        client.publish(self.publish_topic ,payload=f'base station mac connected: {MAC}',qos=0)

        client.loop_forever()


    def on_connect(self, client, userdata, flags, rc):
        '''连接成功回调'''
        logger.info('Connected with result code '+str(rc))
        client.subscribe(self.subscription_topic)

    def on_message(self, client, userdata, msg):
        '''消息接收回调
        基站升级
        parse_msg: {"task_type": "gateways_upgrade","downlink_task_id": "4", "task_id": "2", "data": {"file_url": "http://192.168.88.34:33332/", "gateways_list": ["917B1D71", "9759A47A"]	}}
        传感器升级
        {"task_type": "sensor_upgrade", "sensor_mac": "917B1D71", "downlink_task_id": "4", "task_id": "3", "data": {"file_url": "http://192.168.88.34:33332/","devaddr_list": ["917B1D71", "9759A47A"]}}
        基站信息提交
        {"task_type": "gateways_info",  "downlink_task_id": "4", "task_id": "333", "data": {"gateway_mac": "E45F01FFFE422525"}}
        {"task_type": "sync_not_submitted",  "data": {"timestamp": "111111"}}
        '''

        logger.info("接收任务：")
        logger.info(msg.payload.decode())

        parse_msg = json.loads(msg.payload.decode())

        logger.info("传感器升级任务：")
        logger.info(parse_msg)
        logger.info(type(parse_msg))

        if parse_msg.get("task_type") == "gateways_upgrade": # 基站升级

            url = parse_msg["data"]["file_url"]

            if gateways_upgrade(url):

                parse_msg["status"] = "success"

                client.publish(self.publish_topic ,payload=json.dumps(parse_msg), qos=0)

            else:

                parse_msg["status"] = "fail"

                client.publish(self.publish_topic ,payload=json.dumps(parse_msg), qos=0)


        if parse_msg.get("task_type") == "sensor_upgrade": # 传感器升级

            if downland_remote_files(parse_msg["data"]["file_url"]) == 0:

                parse_msg["status"] = "fail"
                parse_msg["massage"] = "下载失败"

                client.publish(self.publish_topic ,payload=json.dumps(parse_msg), qos=0)

                return

            filename = os.path.basename(urlparse(parse_msg["data"]["file_url"]).path)

            logger.info(f"升级文件名称：{filename}")

            uc = UpdateSensorWebSocketClient(parse_msg["sensor_mac"], parse_msg["downlink_task_id"], filename)

            threading.Thread(target=uc.connect).start()


        if parse_msg.get("task_type") == "gateways_info": # 基站信息提交

            ns = Ns("127.0.0.1:8080")

            result = {
                "nodes": ns.get_all_nodes(),
                "events": ns.get_event(),
                "lora_net":{} #TODO
            }

            parse_msg["return_data"] = result

            client.publish(self.publish_topic ,payload=json.dumps(parse_msg), qos=0)

        if parse_msg.get("task_type") == "sync_not_submitted":

            ns = Ns("127.0.0.1:8080")

            lst = ns.get_rxframes_list_by_timestamp(int(parse_msg["data"]["timestamp"]))

            for i in lst:

                logger.info(i)

                client.publish(MQTT_LOCAL_PUBLISH_TOPIC ,payload=json.dumps(i), qos=0)



            
if __name__ == "__main__":

    logger.info(f"MQTT_LOCAL_SUBSCRIPTION_TOPIC: {MQTT_LOCAL_SUBSCRIPTION_TOPIC}")

    r = SubscriptionMainBaseServer(MQTT_LOCAL_SUBSCRIPTION_TOPIC, MQTT_LOCAL_PUBLISH_TOPIC)

    r.connect_mqtt()